const {
	config
} = require('../../common/config.js')
const ServerError = require('../../common/error')
const jwt = require('jwt-simple')

const md5 = require('js-md5')

const db = uniCloud.database();

function _payload(params) {
	let payload = {
		_id: params._id,
		username: params.username,
		curtime: params.curtime,
		tokentimeout: params.curtime + config.tokenTimeout
	}
	return payload
}

async function login() {
	let curtime = Date.now()
	let httpInfo = this.getHttpInfo()
	let {
		username,
		password
	} = JSON.parse(httpInfo.body)

	let md5Pwd = md5(config.secret + password)
	let {
		affectedDocs,
		data
	} = await db.collection("admin-user").where({
		username: username,
		password: md5Pwd
	}).get()

	if (affectedDocs == 1) {
		let adminUser = data[0]
		let token = jwt.encode(_payload({
			_id: adminUser._id,
			username: adminUser.username,
			curtime
		}), config.secret)

		let {
			updated
		} = await db.collection("admin-user").doc(adminUser._id).update({
			token: token,
			logintime: curtime
		})
		return {
			errCode: 0,
			data: {
				_id: adminUser._id,
				username: adminUser.username,
				role: adminUser.roles,
				avatarUrl: adminUser.avatarUrl,
				tel: adminUser.tel
			},
			token,
			updated,
			outTime: curtime + config.tokenTimeout,
			errMsg: "登录成功"
		}
	} else {
		return {
			errCode: 101,
			token: "",
			curtime,
			errMsg: "账号密码错误"
		}
	}


}

async function refreshToken() {
	let curtime = Date.now()
	let httpInfo = this.getHttpInfo()
	let token = httpInfo.headers.token
	let user = jwt.decode(token, config.secret)
	let {
		affectedDocs,
		data
	} = await db.collection("admin-user").doc(user._id).get()
	if (data.length > 0) {
		let token = jwt.encode(_payload({
			_id: user._id,
			username: user.username,
			curtime
		}), config.secret)
		let {
			updated
		} = await db.collection("admin-user").doc(user._id).update({
			token: token
		})
		return {
			errCode: 0,
			token,
			outTime: curtime + config.tokenTimeout,
			errMsg: "刷新成功"
		}
	} else {
		return {
			errCode: 2000,
			errMsg: "未知原因刷新失败"
		}
	}

}
async function loginout() {
	let httpInfo = this.getHttpInfo()
	let token = httpInfo.headers.token
	let user = jwt.decode(token, config.secret)
	let {
		updated
	} = await db.collection("admin-user").doc(user._id).update({
		token: ""
	})
	if (updated) {
		return {
			errCode: 0,
			errMsg: "退出"
		}
	} else {
		throw new ServerError("不能重复退出", 3003)
	}

}
module.exports = {
	login,
	loginout,
	refreshToken
}
